<?php
	/**
	 * Страница рассчета запасов.
	 * 
	 * @author Костин Алексей Васильевич aka Volt(220)
	 * @copyright Copyright (c) 2010, Костин Алексей Васильевич
	 * @license http://www.gnu.org/licenses/gpl-3.0.html GNU Public License
	 * @version 1.0
	 * @package HomeMoney
	 */

	/**
	 * Подключение настроек. 
	 */
	require_once("../ini.php");
	$curTab=0;
	
	$DBCon=SQLDBFactory::getDB();
	
	$sql="select 
		item as Товар, 
		cat as Категория, 
		round((kol-lastKol)/(maxD-minD), 3) as `Расход в день`,
		greatest(kol-(curdate()-minD)*round((kol-lastKol)/(maxD-minD), 3),0) as Запас
		from goods
			LEFT OUTER JOIN categ ON goods.id_cat = categ.id
			LEFT OUTER JOIN (select id_good,  round(sum(col),3) as kol, round(sum(sum),2) as sum from basket group by id_good) as t1 on t1.id_good=goods.id
			LEFT OUTER JOIN (select id_good, max(date) as maxD, min(date) as minD 
				from basket 
				LEFT OUTER JOIN buys ON buys.id = basket.id_buy 
				group by id_good) as t2 on t2.id_good=goods.id
			LEFT OUTER JOIN (select col as lastKol, date, id_good
				from basket 
				LEFT OUTER JOIN buys ON buys.id = basket.id_buy) as t3 on t3.date=maxD and t3.id_good=goods.id
		where goods.id not in (select id_smth from SpisExceptions where typeEx='g') and
			  categ.id not in (select id_cat from categ_tree where id_par in(select id_smth from SpisExceptions where typeEx='c'))
		order by Запас, Категория, Товар";
	$rez=$DBCon->select($sql);
	$tabs[$curTab]=new TableTpl($rez);
	$tabs[$curTab]->title= "Промежуток времени";
	$curTab++;
		
	$bodyTpl=new Template(DOCROOT."/Templates/tablesPrint.tpl");
	$bodyTpl->tables=$tabs;
	
	$pageT="Расход и запасы";
	include (DOCROOT."/pages.php"); 
?>